package com.zxl.listener;

import com.rabbitmq.client.Channel;
import com.zxl.constants.MQConstants;
import com.zxl.constants.RedisConstants;
import com.zxl.service.SmsService;
import com.zxl.vo.Sms;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * @packageName com.zxl.listener
 * @ClassName
 * @Author zxl
 * @Description //TODO
 * @date
 **/
@Component
public class MQListener {
    @Autowired
    private SmsService smsService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @RabbitListener(queues = MQConstants.AUTH_QUEUE)
    public void sms(Sms sms, Channel channel, Message message) throws IOException {
        try {
            String routingKey = message.getMessageProperties().getReceivedRoutingKey();
            if (routingKey != null) {
                switch (routingKey) {
                    case "auth.reg":
                        System.out.println(sms);
                        smsService.send(sms);
                        redisTemplate.opsForValue().set(RedisConstants.PHONE_CODE_KEY+sms.getPhone(),
                                sms.getCode(),
                                60,
                                TimeUnit.SECONDS);
                        break;
                }
            }
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (IOException e) {
            channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, true);
            e.printStackTrace();
        }
    }


}
